<template>
	<view class="">
		<view class="card">
			<view class="itemtitle">
				{{$z.$t("充电方式")}}
			</view>

			<view class="button-group">
				<view class="charge-button" :class="{ active: selectedChargeType === 'immediate' }"
					@click="selectedCharge('immediate')">
					立即充电
				</view>
				<view class="charge-button" :class="{ active: selectedChargeType === 'reservation' }"
					@click="selectedCharge('reservation')">
					预约充电
				</view>
			</view>
			<view v-if="selectedChargeType == 'reservation' ">
				<view>
					<view class="title">
						{{$z.$t("选择充电时段")}}
					</view>
					<u--form labelPosition="left" :model="model" :rules="rules" ref="uForm">
						<u-form-item v-for="(field, index) in timeFields" :key="index" :label="field.label"
							:prop="field.prop" borderBottom @click="shows[field.showKey] = true">
							<u--input v-model="model.form[field.modelKey]" disabledColor="#ffffff"
								:placeholder="`请选择${field.label}`" border="none"></u--input>
							<u-icon slot="right" name="arrow-right"></u-icon>
						</u-form-item>
					</u--form>

					<u-datetime-picker v-for="(field, index) in timeFields" :key="index" :show="shows[field.showKey]"
						v-model="timeValues[field.timeKey]" @confirm="handleTimeConfirm($event, field)"
						@cancel="shows[field.showKey] = false" mode="datetime" :min-date="minDate"
						:max-date="maxDate" />
				</view>
				<view class="fee-preview" v-if="selectedChargeType === 'reservation' && fee > 0">
					预约超时费用：{{ fee.toFixed(2) / 100 }} 元
				</view>
				<view>
					<view class="title">
						温馨提示:
					</view>
					<view style="margin-bottom: 10rpx;line-height: 44rpx;">
						1、可预约时段：
						<span v-if="isAllDay">
							全天 <span class="all-day-tag">24小时;</span>
						</span>
						<span v-else>
							{{ StationHD.caryysjs1 | formatTime }}至{{ StationHD.caryysje1 | formatTime }}
							<span v-if="StationHD.caryysjs2 && isTime2" style="margin-left: 10rpx;">
								{{ StationHD.caryysjs2 | formatTime }}至{{ StationHD.caryysje2 | formatTime }}
							</span>
						</span>
					</view>
					<view style="margin-bottom: 10rpx;line-height: 44rpx;">
						2、每天最多可预约{{StationHD.caryycs}}次;
					</view>
					<view style="margin-bottom: 10rpx;line-height: 44rpx;">
						3、"支付金额" 和 "结束时间" 有一方先到就停止充电;
					</view>
					<view style="margin-bottom: 10rpx;line-height: 44rpx;" v-if="StationHD.caryycsje > 0">
						4、预约{{StationHD.caryymfsc}}分钟之内免费，超过{{StationHD.caryymfsc}}分钟后每{{StationHD.caryycssj}}分钟{{StationHD.caryycsje / 100}}元。
					</view>
				</view>
			</view>

		</view>
	</view>
</template>

<script>
	export default {
		name: "yycd",
		props: {
			gtel: {
				type: String,
				default: () => {},
			},
		},
		data() {
			return {
				fee: 0,
				minDate: this.getMinDate(),
				maxDate: this.getMaxDate(),
				timeSlots: [],
				selectedChargeType: 'immediate', // 默认选中立即充电
				model: {
					form: {
						startTime: '',
						endTime: ''
					},
				},
				rules: {
					'form.startTime': [{
							required: true,
							message: '请选择开始时间'
						},
						{
							validator: (rule, value, callback) => this.validateStartTime(rule, value,
								callback),
							trigger: 'change'
						}
					],
					'form.endTime': [{
							required: true,
							message: '请选择结束时间'
						},
						{
							validator: (rule, value, callback) => this.validateEndTimeSameSlot(rule, value,
								callback),
							trigger: 'change'
						},
						{
							validator: 'validateEndTimeAfterStart',
							trigger: 'change'
						}
					]
				},
				timeFields: [{
						label: '开始时间',
						prop: 'form.startTime',
						showKey: 'start',
						modelKey: 'startTime',
						timeKey: 'start'
					},
					{
						label: '结束时间',
						prop: 'form.endTime',
						showKey: 'end',
						modelKey: 'endTime',
						timeKey: 'end'
					}
				],
				shows: {
					start: false,
					end: false
				},
				timeValues: {
					start: null,
					end: null
				},
				ChargeCarSys: {},
				timeDisabled1: [],
				timeDisabled2: [],
				StationHD: {},
				isValid: false,
				isTime2: true,
			}
		},
		filters: {
			formatTime(timeStr) {
				return timeStr?.slice(0, 5) || '' // 使用可选链操作符避免空值
			},
		},
		computed: {
			isAllDay() {
				// 辅助函数：将时间字符串转换为分钟数（忽略秒）
				const timeToMinutes = (timeStr) => {
					if (!timeStr) return 0;
					const [hours, minutes] = timeStr.split(':').map(Number);
					return hours * 60 + minutes;
				};

				// 获取各时间段的分钟表示
				const start1 = timeToMinutes(this.StationHD.caryysjs1);
				const end1 = timeToMinutes(this.StationHD.caryysje1);
				const start2 = timeToMinutes(this.StationHD.caryysjs2);
				const end2 = timeToMinutes(this.StationHD.caryysje2);
				console.log('start1', start1, end1, start2, end2)
				// 全天条件1：单时段覆盖全天 (00:00-23:59)
				const isFullDay = start1 === 0 && end1 >= 1439; // 1439 = 23*60+59

				// 全天条件2：两时段连续覆盖全天
				const isContinuous =
					start1 === 0 &&
					end1 >= 0 &&
					start2 === end1 && // 第二段紧接着第一段
					end2 >= 1439;

				return isFullDay || isContinuous;
			}

		},
		mounted() {
			this.search()
		},
		methods: {
			selectedCharge(val) {
				this.selectedChargeType = val
				console.log('val', val)
				let obj = {}
				if (val == 'immediate') {
					// 清除时间相关数据
					this.model.form.startTime = ''
					this.model.form.endTime = ''
					this.timeValues.start = null // 重置为 null 而不是数值
					this.timeValues.end = null // 重置为 null 而不是数值
					this.fee = 0

					obj = {
						b_yy: 0,
						sjyys: '',
						sjyye: '',
						isValid: false,
					}
				} else {
					obj = {
						b_yy: 1,
						sjyys: '',
						sjyye: '',
						isValid: false,
					}
				}
				this.$emit('change', obj)
			},
			// 新增时间段验证方法
			validateStartTime(rule, value, callback) {
				if (!value) return
				const startMinutes = this.getTimeString(this.timeValues.start)
				const slot = this.findTimeSlot(startMinutes);
				if (!slot) {
					callback(new Error('开始时间不在可预约时段内'));
				} else {
					callback();
				}
			},
			validateEndTimeSameSlot(rule, value, callback) {
				// 确保开始和结束时间都已选择
				if (!this.timeValues.start || !this.timeValues.end) {
					callback();
					return;
				}

				// 将时间戳转换为Date对象
				const startDate = new Date(this.timeValues.start);
				const endDate = new Date(this.timeValues.end);

				// 1. 完整日期时间比较（年月日时分秒）
				if (endDate <= startDate) {
					callback(new Error('结束时间必须晚于开始时间'));
					return;
				}

				// 2. 时间段验证（保持原有逻辑）
				const startMinutes = this.getTimeString(this.timeValues.start)
				const endMinutes = this.getTimeString(this.timeValues.end);
				const slot = this.findTimeSlot(endMinutes);

				// 判断是否为同一天
				const isday = this.isSameDay(this.timeValues.start, this.timeValues.end)

				// 查找开始时间所在时段
				const startSlot = this.findTimeSlot(startMinutes);

				if (isday) {
					if (!slot) {
						callback(new Error('结束时间不在可预约时段内'));
						return;
					}

					// 3. 时段内验证
					const isSameSlot = endMinutes >= startSlot.start &&
						endMinutes <= startSlot.end;

					if (!isSameSlot) {
						callback(new Error('结束时间必须与开始时间在同一时段内'));
					} else {
						callback();
					}
				} else {
					if (!slot) {
						callback(new Error('结束时间不在可预约时段内'));
					} else {
						callback();
					}
				}
			},

			validateEndTimeAfterStart(rule, value, callback) {

				const startMinutes = this.timeValues.start;
				const endMinutes = this.timeValues.end;

				if (endMinutes <= startMinutes) {
					callback(new Error('结束时间必须晚于开始时间'));
				} else {
					callback();
				}
			},
			// 查找时间所在时间段
			findTimeSlot(minutes) {
				for (const slot of this.timeSlots) {
					if (minutes >= slot.start && minutes <= slot.end) {
						return slot;
					}
				}
				return null;
			},
			getMinDate() {
				const now = new Date();
				now.setSeconds(0, 0);
				now.setMinutes(now.getMinutes() + 10); // 增加10分钟偏移
				return now.getTime();
			},
			getMaxDate() {
				const now = new Date();
				const tomorrow = new Date(now);
				tomorrow.setDate(tomorrow.getDate() + 1); // 明天
				tomorrow.setHours(23, 59, 59, 999); // 设置到明天23:59:59
				return tomorrow.getTime();
			},

			showTime() {
				this.show = true
			},
			isFullAfter(start, end) {
				return new Date(end) > new Date(start);
			},
			async search() {
				let ChargeCarSys = await this.$z.request("/ChargeCarSys", {
					gtel: this.gtel,
				});
				this.ChargeCarSys = ChargeCarSys[0]
				console.log('ChargeCarSys[0]', ChargeCarSys[0])
				let StationHD = await this.$z.request("/StationHD", {
					id: this.ChargeCarSys.pcs,
				});
				this.StationHD = StationHD[0]
				this.timeDisabled1 = [this.timeToMinutes(this.StationHD.caryysjs1), this.timeToMinutes(this.StationHD
					.caryysje1)];
				this.timeDisabled2 = [this.timeToMinutes(this.StationHD.caryysjs2), this.timeToMinutes(this.StationHD
					.caryysje2)];
				if (this.StationHD.caryysjs1 && this.StationHD.caryysje1) {
					this.timeSlots.push({
						start: this.timeToMinutes(this.StationHD.caryysjs1),
						end: this.timeToMinutes(this.StationHD.caryysje1)
					});
				}
				if (this.StationHD.caryysjs2 && this.StationHD.caryysje2) {
					// 只有当两个值都不是"00:00:00"时才添加到时间段
					if (this.StationHD.caryysjs2 !== "00:00:00" || this.StationHD.caryysje2 !== "00:00:00") {
						this.timeSlots.push({
							start: this.timeToMinutes(this.StationHD.caryysjs2),
							end: this.timeToMinutes(this.StationHD.caryysje2)
						});
					} else {
						this.isTime2 = false
					}
				}
				console.log('this.timeSlots1231231231231231', this.StationHD.caryysjs2, this.StationHD.caryysje2, this
					.timeSlots)
			},

			handleTimeConfirm(val, field) {
				// 改进正则，确保秒被正确替换为00
				const formattedTime = val.t.replace(/(:\d{2}):\d{2}\.\d+$/, '$1:00');
				this.model.form[field.modelKey] = formattedTime;
				console.log('[val]', this.model.form.startTime)
				// 计算总分钟数
				const timePart = formattedTime.split(' ')[1];
				const [hours, minutes] = timePart.split(':').map(Number);
				this.timeValues[field.timeKey] = hours * 60 + minutes;
				this.shows[field.showKey] = false;
				//计算超时费用
				let fee = 0
				if (this.selectedChargeType === 'reservation') {
					const now = new Date()
					now.setSeconds(0, 0)
					const reserveDate = new Date(this.model.form.startTime)
					reserveDate.setSeconds(0, 0)
					const diffMs = reserveDate - now
					if (diffMs < 0) {
						this.isValid = true
						this.$u.toast('不能选择过去的时间')
						return
					}
					const totalMinutes = Math.floor(diffMs / (1000 * 60))
					// 计算超时分钟
					const freeMinutes = this.StationHD.caryymfsc || 0
					const overtime = totalMinutes - freeMinutes
					console.log('overtime', overtime)
					if (overtime <= 0) {
						this.fee = 0
					} else {
						const chargeUnit = this.StationHD.caryycssj
						const unitPrice = this.StationHD.caryycsje
						if (this.StationHD.caryycssj == 0) {
							this.fee = 0
						} else {
							this.fee = Math.ceil(overtime / chargeUnit) * unitPrice
						}
					}
				}


				// 确保数据更新后触发验证
				this.$nextTick(async () => {
					// 触发字段验证
					await this.$refs.uForm.validateField(field.prop);
					// 新增：触发表单整体验证
					const formValid = await this.validateForm();
					const obj = {
						b_yy: this.selectedChargeType == 'immediate' ? 0 : 1,
						sjyys: this.model.form.startTime,
						sjyye: this.model.form.endTime,
						isValid: formValid,
						caryymfsc: this.StationHD.caryymfsc,
						caryycssj: this.StationHD.caryycssj,
						caryycsje: this.StationHD.caryycsje / 100,
						caryycs: this.StationHD.caryycs,
						fee: this.fee,
					}
					console.log('obj', obj)
					this.$emit('change', obj)
				});
			},
			// 在methods中添加这个方法
			async validateForm() {
				try {
					// 触发表单整体验证
					await this.$refs.uForm.validate();
					return true; // 验证通过
				} catch (errors) {
					return false; // 验证不通过
				}
			},
			timeToMinutes(timeStr) {
				const [hours, minutes] = timeStr.split(':').map(Number);
				return hours * 60 + minutes;
			},
			timestampToTimeString(timestamp) {
				const date = new Date(timestamp);

				// 将秒和毫秒归零
				date.setSeconds(0);
				date.setMilliseconds(0);

				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');

				return `${year}-${month}-${day} ${hours}:${minutes}:00`;
			},
			getTimeString(val) {
				//接受时间戳格式数据 并转化为分钟
				const fullTime = this.timestampToTimeString(val)
				const timePart = fullTime.split(' ')[1] // 示例："15:30:00"
				const cleanTime = timePart.replace(/:\d{2}$/, '') // 移除秒数 → "15:30"
				return this.timeToMinutes(cleanTime)
			},
			//判断年月日是否为同一天
			isSameDay(timestamp1, timestamp2) {
				const date1 = new Date(timestamp1);
				const date2 = new Date(timestamp2);

				// 直接比较年月日
				return date1.getFullYear() === date2.getFullYear() &&
					date1.getMonth() === date2.getMonth() &&
					date1.getDate() === date2.getDate();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.card {
		background: #fff;
		margin: 30rpx;
		border-radius: 20rpx;
		padding: 26rpx;
	}

	.itemtitle {
		font-weight: 600;
		font-size: 32rpx;
		color: #333;
		margin-bottom: 30rpx;
	}

	.title {
		font-size: 32rpx;
		color: #333;
		margin: 30rpx 0;
	}

	.button-group {
		display: flex;
		gap: 20rpx;
	}

	.charge-button {
		flex: 1;
		height: 80rpx;
		border: 1rpx solid #ddd;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		color: #333;
		background: #fff;
		transition: all 0.3s;

		&.active {
			background: #007AFF;
			color: #fff;
			border-color: #007AFF;
		}
	}

	.fee-preview {
		margin-top: 20rpx;
		color: #007AFF;
	}

	::v-deep .u-form-item__body {
		padding: 0;
	}
</style>